from django.core.paginator import Paginator
from django.db.models import Q
from django.shortcuts import render

from record.models import Record


def normalize(carno):
    return carno.replace(' ', '').upper()


def search(request):
    records = []
    if request.method == 'POST':
        carno = normalize(request.POST.get('carno'))
        if carno:
            queryset = Record.objects.filter(
                Q(carno=carno) | Q(owner__contains=carno)
            )
        else:
            queryset = Record.objects.all()
        paginator = Paginator(queryset, 5)
        records = paginator.page(1).object_list
    return render(request, 'index.html', {'records': records})

